﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.WebHelper;
using RestSharp;

/**
 * 创建时间：2015/1/14 11:02:25
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace ComicIsland.App.CIHelper
{
    public delegate void WinPhoneDataUpdateResult(KEYS.WpDataUpdateType updateType, bool result, string message);

    public class WinPhoneDataUpdateHelper
    {
        public event WinPhoneDataUpdateResult OnWinPhoneDataUpdateResult;
        private string tmpHOST = "http://58.215.139.195";

        public WinPhoneDataUpdateHelper()
        {
        }


        /// <summary>
        /// 收藏夹同步处理
        /// </summary>
        /// <param name="wpType"></param>        
        /// <param name="syncBook"></param>
        /// <param name="bookcaseInfo"></param>
        public void SyncBookcaseInfo(KEYS.WpDataUpdateType wpType, KEYS.WpDataUpdateTypeSyncBook syncBook, LocalBookcaseInfo bookcaseInfo)
        {
            if (!NetworkStatusHelper.IsNetworkAvailable)
            {
                //没有网络的情况下，直接将bookcaseInfo存储即可（标识为未同步）
                new LocalBookcaseInfoHelper().Update(bookcaseInfo);
                return;
            }

            LocalAppConfigInfo appConfigInfo = new LocalAppConfigInfoHelper().Get();
            if (!(appConfigInfo != null && appConfigInfo.WpId > 0))
            {
                new LocalBookcaseInfoHelper().Update(bookcaseInfo);
                LogHelper.LogError("AppConfigInfo or WpId is empty!");
                return;
            }
            //
            string requestUrl = string.Concat(this.tmpHOST, "/comic/wpdataupdate", "?", KEYS.REQUEST_QUERY_PLATFORM);
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("type", KEYS.WpDataUpdateType.bookHandle.ToString());
            parameters.Add("wpId", appConfigInfo.WpId);
            if (syncBook == KEYS.WpDataUpdateTypeSyncBook.Add)
            {
                parameters.Add("addBooks", string.Format("[{0}]", bookcaseInfo.BookId));
                parameters.Add("deleteBooks", "[]");
            }
            if (syncBook == KEYS.WpDataUpdateTypeSyncBook.Deleted)
            {
                parameters.Add("addBooks", "[]");
                parameters.Add("deleteBooks", string.Format("[{0}]", bookcaseInfo.BookId));
            }
            //
            #region 与服务器进行数据同步
            PostClientHelper proxy = new PostClientHelper(parameters);
            LogHelper.LogInfo("PostData" + proxy.PostData.ToString());
            LogHelper.LogInfo(requestUrl + "\t" + proxy.PostData.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    if (e.Error != null)
                    {
                        new LocalBookcaseInfoHelper().Update(bookcaseInfo);
                        LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                        if (this.OnWinPhoneDataUpdateResult != null)
                        {
                            this.OnWinPhoneDataUpdateResult(wpType, false, e.Error.Message);
                        }
                        return;
                    }

                    #region ********************获取结果处理********************
                    string result = e.Result;

                    if (string.IsNullOrWhiteSpace(result))
                    {
                        new LocalBookcaseInfoHelper().Update(bookcaseInfo);
                        if (this.OnWinPhoneDataUpdateResult != null)
                        {
                            this.OnWinPhoneDataUpdateResult(wpType, false, "未获取到数据！");
                        }
                        LogHelper.LogError("Result is empty.");
                        return;
                    }
                    //
                    if (result.StartsWith("exception:"))
                    {
                        new LocalBookcaseInfoHelper().Update(bookcaseInfo);
                        LogHelper.LogError(result);
                        if (this.OnWinPhoneDataUpdateResult != null)
                        {
                            this.OnWinPhoneDataUpdateResult(wpType, false, "网络连接失败！");
                        }
                        return;
                    }
                    LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                    //
                    var rootCharacterString = JSONHelper.Deserialize<JsonComicWinPhoneUpdate>(result);
                    if (0 != rootCharacterString.Code)
                    {
                        new LocalBookcaseInfoHelper().Update(bookcaseInfo);
                        if (this.OnWinPhoneDataUpdateResult != null)
                        {
                            this.OnWinPhoneDataUpdateResult(wpType, false, rootCharacterString.CodeMsg);
                        }
                    }
                    else
                    {
                        if (syncBook == KEYS.WpDataUpdateTypeSyncBook.Deleted)
                        {
                            //直接从收藏夹中移除
                            new LocalBookcaseInfoHelper().Remove(bookcaseInfo.ComicId);
                        }
                        else
                        {
                            bookcaseInfo.IsSync = true;
                            bookcaseInfo.SyncUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD);
                            new LocalBookcaseInfoHelper().Update(bookcaseInfo);
                            if (this.OnWinPhoneDataUpdateResult != null)
                            {
                                this.OnWinPhoneDataUpdateResult(wpType, true, rootCharacterString.CodeMsg);
                            }
                        }
                    }
                    #endregion ********************获取结果处理********************
                }
                catch
                {

                }
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
            #endregion 与服务器数据同步

        }




        public void InvokeInterface(KEYS.WpDataUpdateType wpType, LocalAppConfigInfo appConfigInfo, KEYS.WpDataUpdateTypeSyncBook syncBook = KEYS.WpDataUpdateTypeSyncBook.Add, LocalBookcaseInfo bookcaseInfo = null)
        {
            if (!NetworkStatusHelper.IsNetworkAvailable)
            {
                LogHelper.LogError("未连接网络！");
                return;
            }
            if (appConfigInfo == null)
            {
                LogHelper.LogError("AppConfigInfo is empty!");
                return;
            }
            //string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/wpdataupdate", "?", KEYS.REQUEST_QUERY_PLATFORM);
            string requestUrl = string.Concat("http://58.215.139.195", "/comic/wpdataupdate", "?", KEYS.REQUEST_QUERY_PLATFORM);

            Dictionary<string, object> parameters = new Dictionary<string, object>();

            if (wpType == KEYS.WpDataUpdateType.sync)
            {
                parameters.Add("type", KEYS.WpDataUpdateType.sync.ToString());
                parameters.Add("channelurl", appConfigInfo.PushChannelUrl);
                parameters.Add("ispush", appConfigInfo.IsPush);
                parameters.Add("deviceuniqueid", DeviceInfoHelper.GetDeviceUniqueIDToHex);
                parameters.Add("devicename", DeviceInfoHelper.GetDeviceName);
                parameters.Add("devicemanufacturer", DeviceInfoHelper.GetDeviceManufacturer);
                parameters.Add("osversion", DeviceInfoHelper.GetDeviceOS);
                parameters.Add("syncdate", appConfigInfo.SyncData);
                //parameters.Add("useragent", "");
                //parameters.Add("addBooks", "");
                //parameters.Add("deleteBooks", "");
            }
            else
            {
                if (appConfigInfo.WpId <= 0)
                {
                    if (this.OnWinPhoneDataUpdateResult != null)
                    {
                        this.OnWinPhoneDataUpdateResult(wpType, false, "WpId is empty.");
                    }
                    return;
                }
                if (wpType == KEYS.WpDataUpdateType.bookHandle)
                {
                    parameters.Add("type", KEYS.WpDataUpdateType.bookHandle.ToString());
                    parameters.Add("wpId", appConfigInfo.WpId);
                    if (syncBook == KEYS.WpDataUpdateTypeSyncBook.Add)
                    {
                        parameters.Add("addBooks", string.Format("[{0}]", bookcaseInfo.BookId));
                        parameters.Add("deleteBooks", "[]");
                    }
                    if (syncBook == KEYS.WpDataUpdateTypeSyncBook.Deleted)
                    {
                        parameters.Add("addBooks", "[]");
                        parameters.Add("deleteBooks", string.Format("[{0}]", bookcaseInfo.BookId));
                    }
                }
                else if (wpType == KEYS.WpDataUpdateType.updateChannelurl)
                {
                    parameters.Add("type", KEYS.WpDataUpdateType.updateChannelurl.ToString());
                    parameters.Add("wpId", appConfigInfo.WpId);
                    parameters.Add("channelurl", appConfigInfo.PushChannelUrl);
                }
                else if (wpType == KEYS.WpDataUpdateType.updateOptions)
                {
                    parameters.Add("type", KEYS.WpDataUpdateType.updateOptions.ToString());
                    parameters.Add("wpId", appConfigInfo.WpId);
                    parameters.Add("ispush", appConfigInfo.IsPush);
                }
            }
            PostClientHelper proxy = new PostClientHelper(parameters);
            LogHelper.LogInfo("PostData" + proxy.PostData.ToString());
            LogHelper.LogInfo(requestUrl + "\t" + proxy.PostData.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            //            
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    if (e.Error != null)
                    {
                        LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                        if (this.OnWinPhoneDataUpdateResult != null)
                        {
                            this.OnWinPhoneDataUpdateResult(wpType, false, e.Error.Message);
                        }
                        return;
                    }

                    #region ********************获取结果处理********************
                    string result = e.Result;

                    if (string.IsNullOrWhiteSpace(result))
                    {
                        if (this.OnWinPhoneDataUpdateResult != null)
                        {
                            this.OnWinPhoneDataUpdateResult(wpType, false, "未获取到数据！");
                        }
                        LogHelper.LogError("Result is empty.");
                        return;
                    }
                    //
                    if (result.StartsWith("exception:"))
                    {
                        LogHelper.LogError(result);
                        if (this.OnWinPhoneDataUpdateResult != null)
                        {
                            this.OnWinPhoneDataUpdateResult(wpType, false, "网络连接失败！");
                        }
                        return;
                    }
                    LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());


                    //
                    var rootCharacterString = JSONHelper.Deserialize<JsonComicWinPhoneUpdate>(result);
                    if (0 != rootCharacterString.Code)
                    {
                        if (this.OnWinPhoneDataUpdateResult != null)
                        {
                            this.OnWinPhoneDataUpdateResult(wpType, false, rootCharacterString.CodeMsg);
                        }
                    }
                    else
                    {
                        if (rootCharacterString.Info != null)
                        {
                            LocalAppConfigInfoHelper appConfigInfoHelper = new LocalAppConfigInfoHelper();
                            //其它类型不会返回WpId
                            if (wpType == KEYS.WpDataUpdateType.sync && rootCharacterString.Info.WpId > 0)
                            {
                                appConfigInfo.WpId = rootCharacterString.Info.WpId;
                            }
                            appConfigInfoHelper.AddOrUpdate(appConfigInfo);
                            if (this.OnWinPhoneDataUpdateResult != null)
                            {
                                this.OnWinPhoneDataUpdateResult(wpType, true, rootCharacterString.CodeMsg);
                            }
                        }
                        else
                        {
                            if (this.OnWinPhoneDataUpdateResult != null)
                            {
                                this.OnWinPhoneDataUpdateResult(wpType, false, "wpid is empty");
                            }
                        }
                    }
                    #endregion ********************获取结果处理********************
                }
                catch
                {

                }
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }
    }
}
